<template>
  <div>
    <div style="display: flex; align-items: center; padding-bottom: 20px">
      <el-button v-permission="['sys:depart:add']" class="filter-item" size="small" type="primary" icon="el-icon-plus" @click="formDialog(0)">
        添加
      </el-button>
      <el-input v-model="filterText" size="small" style="width: 200px; margin-left: 10px" placeholder="搜索知识点名称" class="filter-item" />

    </div>

    <el-table
      ref="table"
      :data="tableData"
      :default-expand-all.sync="defaultExpand"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :header-cell-style="{'background':'#f2f3f4', 'color':'#555', 'font-weight':'bold', 'line-height':'32px'}"
      row-key="id"
      border
    >
      <el-table-column label="名称" prop="pointName" />
      <el-table-column label="编码" prop="pointCode" />

      <el-table-column align="center" label="排序" width="150px">
        <template v-slot="scope">
          <el-tooltip v-permission="['sys:depart:update']" class="item" effect="dark" content="向下移动" placement="bottom">
            <el-button size="small" icon="el-icon-sort-down" circle @click="handleSort(scope.row.id, 1)" />
          </el-tooltip>

          <el-tooltip v-permission="['sys:depart:update']" class="item" effect="dark" content="向上移动" placement="bottom">
            <el-button size="small" icon="el-icon-sort-up" circle @click="handleSort(scope.row.id, 0)" />
          </el-tooltip>

        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" width="200px">
        <template v-slot="scope">
          <el-tooltip v-permission="['sys:depart:add']" class="item" effect="dark" content="添加下级知识点" placement="bottom">
            <el-button size="small" icon="el-icon-plus" circle @click="formDialog(scope.row.id)" />
          </el-tooltip>

          <el-tooltip v-permission="['sys:depart:update']" class="item" effect="dark" content="修改" placement="bottom">
            <el-button size="small" icon="el-icon-edit" circle @click="formDialog(scope.row.parentId, scope.row.id)" />
          </el-tooltip>

          <el-tooltip v-permission="['sys:depart:delete']" class="item" effect="dark" content="删除" placement="bottom">
            <el-button size="small" icon="el-icon-delete" circle @click="handleDelete(scope.row.id)" />
          </el-tooltip>

        </template>

      </el-table-column>


    </el-table>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogFormVisible"
      title="维护知识点"
      width="30%"
    >
      <el-form ref="postForm" :model="postForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="知识点名称" prop="pointName">
          <el-input v-model="postForm.pointName" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchDetail, deleteData, saveData, sortData, fetchTree } from '@/api/sys/kp/kp'
import permission from '@/directive/permission'

export default {
  directives: { permission },
  data() {
    return {
      defaultExpand: true,
      postForm: {},
      rules: {
        pointName: [
          { required: true, message: '知识点名称不能为空！' }
        ]
      },
      dialogFormVisible: false,
      tableData: [],
      listLoading: true,
      pointCode: '',
      filterText: '',
      treeList: []
    }
  },
  watch: {

    // 检测查询变化
    filterText: {
      handler(val) {
        this.filterTree(val)
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {

    // 前端搜索
    filterTree(val) {
      const saveList = []
      // 树结构
      if (this.treeList.length === 0) {
        this.treeList = JSON.parse(JSON.stringify(this.tableData))
      }
      // 搜索结果
      this.onFuzzyTreeList('pointName', val, this.treeList, saveList)
      this.tableData = saveList
    },


    /**
       * 编辑窗口
       * @param parentId
       * @param currentId
       */
    formDialog(parentId, currentId) {
      // 清空表单
      this.postForm = {}

      // 覆盖上级分类
      this.postForm.parentId = parentId

      // 如果是修改
      if (currentId != null) {
        fetchDetail(currentId).then(response => {
          this.postForm = response.data
        })
      }

      this.dialogFormVisible = true
    },

    getList() {
      this.listLoading = true
      this.treeList = []
      fetchTree(this.listQuery).then(res => {
        this.tableData = res.data
        this.listLoading = false
      })

      // 清理本地缓存
      localStorage.clear()
    },

    handleSort(id, sort) {
      sortData(id, sort).then(() => {
        this.$notify({
          title: '成功',
          message: '知识点排序成功！',
          type: 'success',
          duration: 2000
        })

        this.getList()
      })
    },

    handleSave() {
      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return
        }

        saveData(this.postForm).then(() => {
          this.$notify({
            title: '成功',
            message: '知识点保存成功！',
            type: 'success',
            duration: 2000
          })

          this.dialogFormVisible = false
          this.getList()
        })
      })
    },

    handleDelete(id) {
      // 删除
      this.$confirm('确实要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        ids.push(id)

        deleteData(ids).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })

          this.getList()
        }).catch(err => {
          console.log(err)
        })
      })
    },

    /**
     * 递归tree关键词搜索
     *
     * @param {key} 需要递归的key名
     * @param {value} 需要搜索查询的关键字
     * @param {treeList} 遍历tree列表
     * @return {saveList} 返回查询数组列表
     */
    onFuzzyTreeList(key, value, treeList, saveList = []) {
      return new Promise((resolve, reject) => {
        treeList.forEach(item => {
          if (item[key].indexOf(value) > -1) {
            saveList.push(item)
          } else {
            if (item.children && item.children.length > 0) {
              const _reData = this.onFuzzyTreeList(key, value, item.children, saveList)
              if (_reData && _reData.length > 0) {
                saveList.push({
                  ...item,
                  children: _reData
                })
              }
            }
          }
        })

        resolve(saveList)
      })
    }

  }
}
</script>
